package com.wonders.frame.service;

import com.gcr.util.StringUtil;
import com.wonders.frame.common.Enum.CommonSourceKeyEnum;
import com.wonders.frame.common.Enum.InitCommonSourceEnum;
import com.wonders.frame.common.Enum.RemovedCodeEnum;
import com.wonders.frame.common.Sorts;
import com.wonders.frame.entity.*;
import com.wonders.frame.entity.Tree.SelectTreeNodeData;
import com.wonders.frame.entity.Tree.TreeNodeData;
import com.wonders.frame.entity.form.AuthPermissionForm;
import com.wonders.frame.repository.AuthPermissionRepository;
import com.wonders.frame.repository.AuthRolePermissionRepository;
import com.wonders.frame.repository.core.CoreRepository;
import com.wonders.frame.service.Core.CoreCurdService;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.transaction.Transactional;
import java.util.*;

@Service
public class AuthPermissionService extends CoreCurdService<AuthPermission> {
    Logger log = LoggerFactory.getLogger(AuthPermissionService.class);
    @Autowired
    private AuthPermissionRepository repo;
    protected CoreRepository getRepository(){
        return repo;
    }

    @Autowired
    private AuthRolePermissionRepository authRolePermissionRepository;
    @Autowired
    private AuthPermissionRepository authPermissionRepository;

    /**
     * 验证权限唯一性
     * @param id
     * @param permissionCode
     * @return
     */
    public Boolean checkUnique(String id,String permissionCode){
        //修改
        if(!StringUtils.isEmpty(id)){
            // 1.如果没修改code 直接返回true 2.修改了code 判断修改后的code是否存在重复值
            AuthPermission authPermission= repo.findById(id).get();
            if(permissionCode.equals(authPermission.getCode())){
                return true;
            }
        }

        //新增和修改都需要判断
        List<AuthPermission> list=repo.findByCodeAndRemoved(permissionCode,RemovedCodeEnum.AVAILABLE.getCode());
        if(CollectionUtils.isEmpty(list)){
            return  true;
        }else {
            return false;
        }
//        List<AuthPermission> list = authPermissionRepository.checkUnique(code, parentId);
//        //改过code,或者新增 需要验证
//        if(list!=null&&list.size()>0){
//            return false;
//        }else{
//            return true;
//        }
    }

    //新增权限
    @Transactional
    public AuthPermission save(AuthPermissionForm authPermissionForm) {
        AuthPermission authPermission=new AuthPermission();
        //把第一个对象的属性拷贝到第二个对象里
        BeanUtils.copyProperties(authPermissionForm,authPermission);
        if(StringUtil.isEmpty(authPermissionForm.getId())){
            log.debug("new user");
            authPermission.setId(StringUtil.getUUID());
            authPermission.setRemoved(RemovedCodeEnum.AVAILABLE.getCode());
            authPermission.setCrtDate(new Date());
        }else{
            //查所有子节点 不设置的话 会把子节点的parentId赋空
            List<AuthPermission> list=repo.findByParentIdAndRemoved(authPermissionForm.getId(),RemovedCodeEnum.AVAILABLE.getCode());
            authPermission.setPerChildren(list);
        }
        authPermission.setUpdDate(new Date());
        log.debug("modify user");
        authPermission=repo.save(authPermission);

        //新增时给admin权限赋权
        if(StringUtil.isEmpty(authPermissionForm.getId())){
            //删除所有权限
            authRolePermissionRepository.deleteByRoleId("1");
            List<AuthPermission> list=repo.findByParentIdAndRemoved("all",RemovedCodeEnum.AVAILABLE.getCode());
            List<AuthRolePermission> authRolePermissionList=new ArrayList<>();
            for(AuthPermission permission:list){
                AuthRolePermission authRolePermission=new AuthRolePermission();
                authRolePermission.setRoleId("1");
                authRolePermission.setPermissionId(permission.getId());
                authRolePermission.setCrtDate(new Date());
                authRolePermission.setUpdDate(new Date());
                authRolePermission.setRemoved(RemovedCodeEnum.AVAILABLE.getCode());
                authRolePermissionList.add(authRolePermission);
            }
            authRolePermissionRepository.saveAll(authRolePermissionList);
        }

        return authPermission;
    }

    //删除权限
    public void deleteByPermissionId(String id){
        if(!StringUtils.isEmpty(id)){
            Map<String, Object> map= InitCommonSourceEnum.getCommonSource(CommonSourceKeyEnum.PERMISSION.name());

            //修改节点删除状态
            AuthPermission authPermission=repo.getOne(id);
            authPermission.setRemoved(RemovedCodeEnum.REMOVED.getCode());
            repo.save(authPermission);

            //删除该权限的所有赋权
            authRolePermissionRepository.deleteByPermissionId(id);

            /*for (Map.Entry<String, Object> entry : map.entrySet()) {
                AuthPermission permission=((AuthPermission) entry.getValue());
                //当前权限的父节点
                if(authPermission.getParentId().equals(permission.getId())&&permission.getRemoved()==RemovedCodeEnum.AVAILABLE.getCode()){
                    int count=0;
                    //判断子节点有几个
                    for(AuthPermission permission1:permission.getPerChildren()){
                        if(RemovedCodeEnum.AVAILABLE.getCode().equals(permission1.getRemoved())){
                            count++;
                        }
                    }
                    //说明父节点下的子节点只有一个或者没有 删除选中权限和父节点权限
                    if(count<2){
                        //删除绑定的父节点权限
                        //删除当前权限
                        authRolePermissionRepository.deleteByPermissionId(id);
                        authRolePermissionRepository.deleteByPermissionId(permission.getId());
                        break;
                    }else{
                        //删除当前权限
                        authRolePermissionRepository.deleteByPermissionId(id);
                    }

                }
            }*/

            InitCommonSourceEnum.INSTANCE.initPermission();
        }
    }

    //根据id查询权限
    public  AuthPermission findById(String id){
        return repo.findById(id).get();
    }

    /**
     * 获得权限树
     * @return
     */
    public List<SelectTreeNodeData> getPermissionTree(){
        List<SelectTreeNodeData> nodes = new ArrayList<SelectTreeNodeData>();
        List<AuthPermission> pers = repo.findByRemovedOrRemovedNull(0);
        for(AuthPermission per : pers){
            // 若存在parentNode，则该节点在child中显示，不需要加到根节点中
            if(per.getParentId() == null){
                nodes.add(getPermissionNode(per));
            }
        }
        return nodes;
    }


    /**
     * 递归调用，初始化权限树菜单
     * @param per
     * @return
     */
    private SelectTreeNodeData getPermissionNode(AuthPermission per){
        SelectTreeNodeData nodeData = new SelectTreeNodeData();
        nodeData.setKey(per.getId());
        nodeData.setTitle(per.getComponentText());
        nodeData.setValue(per.getId());
        //nodeData.setAuthType(per.getAuthType());
        nodeData.setIcon(per.getComponentIconType());
        //nodeData.setIcon("<Icon type='"+per.getComponentIconType()+"'/>");
        if(per.getPerChildren() != null){
            List<SelectTreeNodeData> nodes = new ArrayList<SelectTreeNodeData>();
            for(AuthPermission p : per.getPerChildren()){
                if(p.getRemoved()!=1){
                    nodes.add(getPermissionNode(p));
                }
            }
            nodeData.setChildren(nodes);
        }
        return nodeData;
    }

    /**
     * 获得左侧权限树菜单
     * @return
     */

    public List<AuthPermission> getAll() {
        return repo.findAll();
    }

    public List<TreeNodeData> getMenuNodeTree() {
        List<TreeNodeData> nodes = new ArrayList<TreeNodeData>();
        List<AuthPermission> pers = repo.findAll();
        for (AuthPermission per : pers) {
            // 若存在parentNode，则该节点在child中显示，不需要加到根节点中
            if (per.getParentId() == null) {
                nodes.add(getMenuNode(per));
            }

        }
        return nodes;
    }

    /**
     * 递归调用，初始化菜单树对象
     * @param per
     * @return
     */
    private TreeNodeData getMenuNode(AuthPermission per) {
        TreeNodeData nodeData = new TreeNodeData();
        nodeData.setKey(per.getId());
        nodeData.setTitle(per.getComponentText());
        if (per.getPerChildren() != null) {
            List<TreeNodeData> nodes = new ArrayList<TreeNodeData>();
            for (AuthPermission p : per.getPerChildren()) {
                nodes.add(getMenuNode(p));
            }
            nodeData.setChildren(nodes);
        }
        return nodeData;
    }

    public String getMenuHtml() {
        StringBuffer sb = new StringBuffer();
        //List<TreeNodeData> treeData = getMenuNodeTree();
        List<AuthPermission> pers = repo.findAll();
        for (AuthPermission per : pers) {
            // 若存在parentNode，则该节点在child中显示，不需要加到根节点中
            if (Objects.equals("all", per.getParentId())) {
                // sb.append("<SubMenu key='"+per.getId()+"' title={<span><Icon type='user' />"+per.getComponentText()+"</span>}>");
                sb = buildMenuChild(sb, per);
                // sb.append("</SubMenu>");
            }

        }
        return sb.toString();
    }

    private StringBuffer buildMenuChild(StringBuffer sb, AuthPermission per) {
        if (per.getPerChildren() != null && per.getPerChildren().size() != 0) {
            sb.append("<SubMenu key='" + per.getId() + "' title={<span><Icon type='user' />" + per.getComponentText() + "</span>}>");
            for (AuthPermission p : per.getPerChildren()) {
                sb = buildMenuChild(sb, p);
            }
            sb.append("</SubMenu>");
        } else {
            sb.append("<Menu.Item key='" + per.getId() + "'>");
            sb.append("<Link to='" + per.getComponentLinkUrl() + "'>" + per.getComponentText() + "</Link>");
            sb.append("</Menu.Item>");
        }
        return sb;
    }

    //模糊查询节点
    public List<SelectTreeNodeData> searchNodeByPermissionName(String permissionName){
        List<Sorts> sortsList=new ArrayList<>();
/*
        sortsList.add(new Sorts("asc","seq"));

        Map<String,Object> map=new HashMap<>();
        map.put("permissionName_like",permissionName);
*/

        List<AuthPermission> list = repo.findByComponentTextLike("%"+permissionName+"%");

        //  List<AuthPermission> list=findAllByParamsAndSort(map,sortsList);
        List<SelectTreeNodeData> nodes = new ArrayList<SelectTreeNodeData>();
        for(AuthPermission permission:list){
            SelectTreeNodeData nodeData=new SelectTreeNodeData();
            nodeData.setKey(permission.getId());
            nodeData.setValue(permission.getId());
            nodeData.setTitle(permission.getComponentText());
            nodeData.setIcon(permission.getComponentIconType());
            nodeData.setChildren(new ArrayList<>());
            nodes.add(nodeData);
        }
        return nodes;
    }
}
